# coding=utf-8

import web

import settings
import utils
import define
import redirect

import models
from controllers.users import UserSession, auth_login
from controllers.users.models import get_user_bind_by_id

frender = settings.FRONT_RENDER

class BeenTo(object):
    """
    灵感信息的“去过”视图
    """
    @auth_login(lite = True)
    def GET(self, id):
        id = utils.intval(id)
        if id <= 0:
            return 'None'

        aff = models.get_afflatus_by_id(id)
        if aff:
            return frender.afflatus.beento(aff)

        return 'None'
    
    @auth_login(lite = True)
    def POST(self, id):
        id = utils.intval(id)
        if id <= 0:
            return self.GET(id)

        # 读取操作的灵感信息
        aff = models.get_afflatus_by_id(id)
        if not aff:
            # 灵感信息无效时
            return 'None'

        ipt = web.input(rating = 0, comment = '', sync = '1')
        # 文本框等于默认值
        # 尽管在客户端做了处理
        # 服务端还是判断一下吧
        if ipt.comment == '说点什么吧...':
            ipt.comment = ''
        
        if models.been_to(id
                , web.ctx.user.uid
                , ipt.rating
                , ipt.comment):
            if ipt.sync == '1':
                # 提交微博内容
                status = None
                # 将评论内容同步到微博
                if ipt.comment:
                    # 输入评论内容
                    status = u'我分享了对%s%s的评论：%s。' % (
                        aff.dest_name,
                        aff.title,
                        ipt.comment,
                    )
                elif ipt.rating > 0:
                    # 打了分的
                    status = u'我去了%s的%s之后，打了%s分。' % (
                        aff.dest_name,
                        aff.title,
                        ipt.rating,
                    )
                else:
                    # 什么都没有输入的情况
                    status = u'我在寻宝图上分享了%s的%s。' % ( 
                                    aff.dest_name,
                                    aff.title,
                                )
                # 补充地址
                status = u'''%(status)s 
                http://xunbaotu.com/afflatus/invite/%(id)s?f=%(bind_type)s&id=%(bind_id)s&action=beento''' % {
                        'status': status,
                        'id': aff.id,
                        'bind_type': web.ctx.user.client.name,
                        'bind_id': web.ctx.user.bind_id,
                    }
                # 同步到微博
                web.ctx.user.client.upload_media_status(status, aff.media_id)

            return redirect.afflatus(id, True)
        else:
            return self.GET(id)

class Invite(object):
    """
    关注灵感后，分享微博中的链接
    视为用户邀请
    """
    def GET(self, id = '0'):
        id = utils.intval(id)
        if id <= 0:
            redirect.home()

        ipt = web.input(id = '0', f = 'sina', action = '')

        bind_id = utils.intval(ipt.id)
        bind_type = ipt.f

        # 获取邀请用户
        usr = get_user_bind_by_id(bind_id, bind_type)
        # 邀请用户无效
        # 跳转到首页
        if not usr:
            redirect.home()
        
        # 读取灵感信息
        aff = models.get_afflatus_by_id(id)
        # 邀请关联的灵感信息无效
        # 跳转到首页
        if not aff:
            redirect.home()

        return frender.afflatus.invite(aff, usr, ipt.action)

class Share(object):
    """
    分享灵感到微博
    """
    @auth_login(lite = True)
    def GET(self, id):

        id = utils.intval(id)
        if id > 0:
            aff = models.get_afflatus_by_id(id)
            if aff:
                comment = u'想去%s的%s啊～还有想去的人儿吗？' %  (
                                    aff.dest_name, 
                                    aff.title,
                                )

                # 渲染视图
                return frender.afflatus.share(aff, comment)

        return redirect.home()

    @auth_login(lite = True)
    def POST(self, id):
        # 跟随微博一起发布的媒体文件
        media_id = 0
        # 是否保存用户提交的附注
        save_comment = False
        comment = web.input().get('comment', None)

        id = utils.intval(id)
        if id > 0:
            aff = models.get_afflatus_by_id(id)
            if aff:
                media_id = aff.media_id
                # 用户是否提供了分享内容
                if not comment or comment.strip() == '':
                    # 如果未提供分享内容
                    # 使用系统生成的内容
                    comment = u'想去%s的%s啊～还有想去的人儿吗？'
                else:
                    # 如果用户自定义了分享内容，那么就保存
                    # 如果是系统提供的内容，就不保存了
                    save_comment = True

        if comment:
            usr = web.ctx.user

            if save_comment:
                # 先保存用户提交的内容到数据库中
                models.add_action_comment(id, usr.uid, 0, comment)

            comment = u'''%(comment)s
                        http://xunbaotu.com/afflatus/invite/%(id)s?f=%(bind_type)s&id=%(bind_id)s''' % {
                            'comment': comment,
                            'id': id,
                            'bind_type': usr.client.name,
                            'bind_id': usr.bind_id
                        }
            usr.client.upload_media_status(comment, media_id)

        return redirect.close_lite()

class Detail(object):
    def GET(self, id):
        """
        显示灵感信息详情
        """
        id = utils.intval(id)
        # 内码无效，跳转到首页去吧
        if id <= 0:
            raise web.seeother('/')

        aff = models.get_afflatus_by_id(id)
        # 读取记录无效
        if not aff:
            raise web.seeother('/')

        # 获取相关灵感信息
        relateds = models.get_related_afflatus(9, id)
        # 获取相邻的前后的灵感信息的id
        adjacents = models.get_afflatus_adjacent_ids(id)

        # 当前会话用户
        session = UserSession.current()
        # 获取当前用户进行过的动作
        actioneds = models.all_actioned_types_by_user(id, session.uid)
        # 是否已经关注
        #followed = models.followed(id, session.uid) and 'yes' or 'no'
        followed = (actioneds and 0 in actioneds) and 'yes' or 'no'
        # 是否去过
        beento = (actioneds and 1 in actioneds) and 'yes' or 'no'

        # 获取显示模式
        mode = web.input().get('mode', '')
        if mode == 'lite':
            return self.render_lite(aff)
        else:
            return self.render(aff, relateds, adjacents, followed, beento)

    def render_lite(self, aff):
        return frender.afflatus.detail_lite(aff)

    def render(self, aff, relateds, adjacents, followed, beento):
        return frender.afflatus.detail(aff
                    , relateds
                    , adjacents, followed, beento)

class Waterfall(object):
    def GET(self, page = '0'):
        """
        瀑布专用读取
        """
        # 页码
        page = utils.intval(page) - 1
        # 一次读取20条
        perpage = 20
        # 读取灵感信息列表
        lst = models.get_all_afflatus(page * perpage, perpage)

        return frender.afflatus.waterfall(lst)

    def POST(self, page = '0'):
        """
        瀑布专用读取
        """
        # 页码
        #page = utils.intval(page) - 1
        # 一次读取20条
        perpage = 20
        # 读取时要排除的灵感信息列表
        excludes = web.input().get('exclude', None)
        # 读取信息列表
        lst = models.get_all_afflatus_rand(perpage, excludes)

        return frender.afflatus.waterfall(lst)
